<?php
class DisplacementController extends CommonController{
	public $order='sort asc';
	public function indexBefore(){
		$this->assign('car_list',M('Car')->oneField('name','id')->select());
		$this->assign('model_list',M('Model')->oneField('name','id')->select());
	}
	public function save() {
		if ($this->isGet ()) {
			$this->display ( $this->tpl );
		} else {
			$db = D ( $this->table );
			$db->create () or $this->error ( $db->getError () );
			$id=$db->save($_POST);
			if(isset($_POST['project_id'])){
				$data=array();
				foreach($_POST['project_id'] as $k=>$v){
					$_data['project_id']=$v;
					$_data['displacement_id']=$id;
					$_data['price']=$_POST['price'][$k];
					$data[]=$_data;
				}
				M('DisplacementProject')->save($data);
			}
			$this->redirect ( 'index' );
		}
	}
	public function update() {
		if ($this->isGet ()) {
			$info = D ( $this->table )->where ( 'id=' . intval ( $_GET ['id'] ) )->find ();
			$this->assign ( 'info', $info );
			$this->display ( 'save' );
		} else {
			$db = D ( $this->table );
			$db->create () or $this->error ( $db->getError () );
			if ($db->update ( $_POST )) {
				$id=intval($_POST['id']);
				M('DisplacementProject')->delete("displacement_id={$id}");
				if(isset($_POST['project_id'])){
					$data=array();
					foreach($_POST['project_id'] as $k=>$v){
						$_data['project_id']=$v;
						$_data['displacement_id']=$id;
						$_data['price']=$_POST['price'][$k];
						$data[]=$_data;
					}
					M('DisplacementProject')->save($data);
				}
				$this->redirect ( 'index' );
			} else {
				$this->error ($db->getError()?$db->getError():'编辑失败' );
			}
		}
	}
	public function saveBefore(){
		if($this->isGet()){
			$this->assign('car_list',M('Car')->order($this->order)->select());
			$this->assign('model_list',json_encode(D('Model')->get_model_list()));
			$this->assign('project_list',M('Project')->order($this->order)->select());
		}
	}
	public function updateBefore(){
		$this->saveBefore();
	}
}